package com.ruis.kotboot.common.base

import com.baomidou.kisso.SSOHelper
import com.baomidou.kisso.security.token.SSOToken
import com.ruis.kotboot.common.core.RuisException
import com.ruis.kotboot.common.util.HttpUtil
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ExceptionHandler
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 控制器基类
 * 支持kisso
 * @author NorthLan at 2018/2/9
 */
abstract class RuisController {
    protected val logger = LoggerFactory.getLogger(this::class.java)

    protected fun getRequest(): HttpServletRequest {
        return HttpUtil.getRequest()
    }

    protected fun getResponse(): HttpServletResponse {
        return HttpUtil.getResponse()
    }

    protected fun getCurUserId(): Long {
        return getSSOToken().id.toLong()
    }

    protected fun getSSOToken(): SSOToken {
        return SSOHelper.attrToken(getRequest())
                ?: throw RuisException(0,"The user does not exist, please re-login.")
    }

    /**
     * 用于处理异常的
     * @return
     */
    @ExceptionHandler(Exception::class)
    fun exception(model: Model, e: Exception): Any {
        logger.error("handler exception:",e)
        model.addAttribute("msg",e.message)
        return "exception"
    }
}